package com.ochnas.volunteersignup.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ochnas.volunteersignup.domain.User;
import com.ochnas.volunteersignup.ui.NewAccountFormHandler;

public class NewAccountServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String submitValue = req.getParameter("button");
		
		if (submitValue != null) {
			if (submitValue.equals("Cancel")) {

				resp.sendRedirect("Login.jsp");
				return;
				
			} else if (submitValue.equals("Save")) {
				
				String emailAddress = req.getParameter("emailAddress");
				String password1 = req.getParameter("password1");
				String password2 = req.getParameter("password2");
				String firstName = req.getParameter("firstName");
				String lastName = req.getParameter("lastName");
				String areaCode = req.getParameter("areaCode");
				String digits1 = req.getParameter("digits1");
				String digits2 = req.getParameter("digits2");
				
				HttpSession session = req.getSession();
				
				NewAccountFormHandler newAccountFormHandler = 
					(NewAccountFormHandler) session.getAttribute("newAccountFormHandler");
				
				newAccountFormHandler.setEmailAddress(emailAddress);
				newAccountFormHandler.setPassword1(password1);
				newAccountFormHandler.setPassword2(password2);
				newAccountFormHandler.setFirstName(firstName);
				newAccountFormHandler.setLastName(lastName);
				newAccountFormHandler.setAreaCode(areaCode);
				newAccountFormHandler.setDigits1(digits1);
				newAccountFormHandler.setDigits2(digits2);
				
				if (newAccountFormHandler.validate()) {
					User u = newAccountFormHandler.createUserAccount();
					if (u!= null) {
						// go to home page
						PrintWriter out = resp.getWriter();
						
						String output = "<html>"
							+"<body>"
								+ "You've successfully created an account for "
								+ emailAddress
							+"</body>"
							+"</html>";
							
							out.println(output);
					} else {
						resp.sendRedirect("NewAccount.jsp");
						return;
						
					}
				} else {
					resp.sendRedirect("NewAccount.jsp");
					return;
				}
			}
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
